//
//  HSYRegisterViewController.m
//  HSY
//
//  Created by 陈浩 on 2017/4/5.
//  Copyright © 2017年 金开门. All rights reserved.
//

#import "HSYRegisterViewController.h"
#import "HSYBaseWebViewController.h"
#import "HSYChooseIndustryViewController.h"
#import "HSYFillInformationViewController.h"
#import "HSYGetVerificationCodeRequest.h"
#import "HSYUserRegisterRequest.h"
#import "BQActivityView.h"
#import "HSYRegisterUserModel.h"
#import "UIImage+Tools.h"
#import "NSString+Validation.h"

@interface HSYRegisterViewController ()<UITextFieldDelegate,UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UITextField *accountTextFiled;
@property (weak, nonatomic) IBOutlet UITextField *identifyingCodeTextFiled;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextFiled;
@property (weak, nonatomic) IBOutlet UITextField *ownedIndustryTextField;
@property (weak, nonatomic) IBOutlet UITextField *shopNameTextField;

@property (weak, nonatomic) IBOutlet UIButton *getIdentifyingCodeBtn;
@property (weak, nonatomic) IBOutlet UIButton *encryptBtn;
@property (weak, nonatomic) IBOutlet UIButton *agreeUserAgreementBtn;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property(nonatomic,assign)NSInteger second;
@property(nonatomic,strong)NSTimer *timer;

@property(nonatomic,strong)HSYRegisterUserModel* userModel;

@end

@implementation HSYRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.leftAreaLBtn setImage:[UIImage imageNamed:@"left"]  forState:UIControlStateNormal];

    [self.titleButton setTitle:@"注册" forState:UIControlStateNormal];
    [self.titleButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    self.accountTextFiled.delegate = self;
    self.passwordTextFiled.delegate = self;
    self.identifyingCodeTextFiled.delegate = self;
    
    self.scrollView.delegate = self;


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
}

- (void)setupNavigationBarBackgroundImage{//设置页面中navigationbar的背景图片
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor] size:CGSizeMake(1, 1)]  forBarMetrics:UIBarMetricsDefault];    
}


- (HSYRegisterUserModel *)userModel{
    if (!_userModel) {
        _userModel = [[HSYRegisterUserModel alloc] init];
    }
    return _userModel;
}

#pragma mark - Action Methods -
//返回登录界面
- (IBAction)goLoginVc:(UIButton *)sender {
    [self.view endEditing:YES];
    [self.navigationController popViewControllerAnimated:YES];
}

//同意用户协议（对勾）
- (IBAction)agreeUserAgreementBtnClick:(id)sender {
    self.agreeUserAgreementBtn.selected = !self.agreeUserAgreementBtn.selected;
}

//密码可见与否
- (IBAction)encryptBtnClick:(UIButton *)sender {
    if (self.passwordTextFiled.secureTextEntry) {
        [self.encryptBtn setImage:[UIImage imageNamed:@"dispaly"] forState:UIControlStateNormal];
        self.passwordTextFiled.secureTextEntry = NO;
    }else{
        [self.encryptBtn setImage:[UIImage imageNamed:@"encrypt"] forState:UIControlStateNormal];
        self.passwordTextFiled.secureTextEntry = YES;
    }
}

//获取验证码
- (IBAction)getIdentifyingCodeBtnClick:(UIButton *)sender {
    [self.view endEditing:YES];
    if (self.accountTextFiled.text.length != 11) {
        [self showMessage:@"请输入正确的手机号"];
        return ;
    }
    
    self.getIdentifyingCodeBtn.enabled = NO;
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateGetIdentifyingCodeBtnText) userInfo:nil repeats:YES]; //启动timer
    
    HSYGetVerificationCodeRequest *task = [[HSYGetVerificationCodeRequest alloc] init];
    task.cellphone = self.accountTextFiled.text;
    task.type = @"1";
    
    __weak typeof(self)weakSelf = self;
    [HSYNetworkManager POST:task success:^(HSYResponse *response) {
        if (response.resultCode != HSY_REQUEST_CODE_SUCCESS) {
            [weakSelf showMessage:response.resultMessage];
            [weakSelf.timer invalidate];
            weakSelf.timer = nil;
            
            weakSelf.getIdentifyingCodeBtn.enabled = YES;
            weakSelf.second = 0;
            [weakSelf.getIdentifyingCodeBtn setTitle:@"获得短信验证码" forState:UIControlStateNormal];
        }
    } failure:nil];
}

//验证码获取倒计时
-(void)updateGetIdentifyingCodeBtnText{
    NSString *time = [NSString stringWithFormat:@"%lds",(long)60- self.second];
    HSYLog(@"%@",time);
    
    [self.getIdentifyingCodeBtn setTitle:time forState:UIControlStateNormal];
    
    if (self.second == 60) {
        [self.timer invalidate];
        self.getIdentifyingCodeBtn.enabled = YES;
        self.second = 0;
        [self.getIdentifyingCodeBtn setTitle:@"重新获得短信验证码" forState:UIControlStateNormal];
        
        return;
    }
    
    self.second++;
}

//查看用户协议
- (IBAction)goUserAgreementVC:(id)sender {
    HSYBaseWebViewController *vc = [[HSYBaseWebViewController alloc] initWithAddress:@"http://hsy.qianbaojiajia.com/text.html" title:@"用户协议"];
    
    [self.navigationController pushViewController:vc animated:YES];
}

//点击注册
- (IBAction)registerBtnClcik:(id)sender {
    
    if (![self checkDataIntegrity]) return; //信息不完善，直接提示错误信息
    
    [BQActivityView showActiviTy];
    
    HSYUserRegisterRequest *task = [HSYUserRegisterRequest mj_objectWithKeyValues:[self.userModel mj_keyValues]];
    
    __weak typeof(self)weakSelf = self;
    [HSYNetworkManager POST:task success:^(HSYResponse *response) {
        [BQActivityView hideActiviTy];

        if (response.resultCode == HSY_REQUEST_CODE_SUCCESS) {
            HSYUserCenter *userCenter = [HSYUserCenter mj_objectWithKeyValues:response.encryptDataResult];
            [userCenter saveUserModelToDocuments];

            //去完善信息
            [weakSelf pushToFillInformation];
        }else{
            [weakSelf showMessage:response.resultMessage];
        }
        
    } failure:^(NSError *error) {
        [BQActivityView hideActiviTy];
        if (error.code != NSURLErrorCancelled) {
            [weakSelf showMessage:@"请求超时"];
        }
    }];
}

//检查信息是否完善
-(BOOL)checkDataIntegrity{
    self.userModel.shopName = self.shopNameTextField.text; //店铺名称
    self.userModel.cellphone = self.accountTextFiled.text; //手机号
    self.userModel.code = self.identifyingCodeTextFiled.text; //验证码
    self.userModel.password = self.passwordTextFiled.text; //设置登录密码
    
    if (self.userModel.shopName.length == 0) {
        [self showMessage:@"请输入店铺名称"];
        return NO;
    }else if(![self.userModel.shopName isValidShopShortName]){
        [self showMessage:@"店铺名称限制为5-25个字数"];
        return NO;
    }
    

    if (self.userModel.industryCode.length == 0) {
        [self showMessage:@"请输入所属行业"];
        return NO;
    }
    
    if (self.userModel.cellphone.length == 0) {
        [self showMessage:@"请输入管理员/店主手机号"];
        return NO;
    }else if(![self.userModel.cellphone isValidPhone]){
        [self showMessage:@"手机号错误，请重新输入"];
        return NO;
    }
    
    
    if (self.userModel.code.length == 0) {
        [self showMessage:@"请输入验证码"];
        return NO;
    }
    
    
    if (self.userModel.password.length == 0) {
        [self showMessage:@"请输入登录密码"];
        return NO;
    }
    
    if (!self.agreeUserAgreementBtn.selected) {
        [self showMessage:@"同意我们的用户协议，才能成为我们的用户"];
        return NO;
    }
    
    
    return YES;
    
}

//选择行业代码
- (IBAction)chooseIndustryBtnClick:(UIButton *)sender {
    [self.view endEditing:YES];
    
    HSYChooseIndustryViewController *vc = [[HSYChooseIndustryViewController alloc] init];
    
    __weak typeof(self)weakSelf = self;
    [vc getIndustrycode:^(NSString *code,NSString *title) {
        weakSelf.userModel.industryCode = code;
        weakSelf.ownedIndustryTextField.text = title;
    }];
    
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - 完善用户信息（推出第一步） -
- (void)pushToFillInformation{
    HSYFillInformationViewController *vc = [[HSYFillInformationViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark UITextFieldDelegate

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField endEditing:YES];
    return YES;
}

#pragma mark - UISCROLLVIEWDELEGATE -

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:[[UIColor whiteColor] colorWithAlphaComponent:self.scrollView.contentOffset.y/172] size:CGSizeMake(1, 1)]  forBarMetrics:UIBarMetricsDefault];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
